package com.haoshuang.zhouzhoubang.ui.page.order.receiveorder.detail

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityReceiveOrderDetailBinding
import com.haoshuang.zhouzhoubang.databinding.ItemServiceItemDetailBinding
import com.haoshuang.zhouzhoubang.model.bean.DetaiBean
import com.haoshuang.zhouzhoubang.model.bean.Image2Bean
import com.haoshuang.zhouzhoubang.model.bean.OrderGoodsBean
import com.haoshuang.zhouzhoubang.model.event.ReceiveOrderSuccess
import com.haoshuang.zhouzhoubang.model.event.RefreshHomeOrderEvent
import com.haoshuang.zhouzhoubang.ui.activity.AppointmentCustomerActivity
import com.haoshuang.zhouzhoubang.ui.activity.AppointmentCustomerActivity2
import com.haoshuang.zhouzhoubang.ui.activity.BondActivity55
import com.haoshuang.zhouzhoubang.ui.activity.ExaminationActivity2
import com.haoshuang.zhouzhoubang.ui.activity.LookActivity
import com.haoshuang.zhouzhoubang.ui.activity.SelectSkillsActivity3
import com.haoshuang.zhouzhoubang.ui.activity.VideoActivity
import com.haoshuang.zhouzhoubang.ui.activity.WarrantyActivity
import com.haoshuang.zhouzhoubang.ui.adapter.ImageAdapter23
import com.haoshuang.zhouzhoubang.ui.dialog.BgxDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.QdDialog
import com.haoshuang.zhouzhoubang.ui.dialog.QdDialog2
import com.haoshuang.zhouzhoubang.ui.dialog.QdDialog3
import com.haoshuang.zhouzhoubang.ui.dialog.QdDialog4
import com.haoshuang.zhouzhoubang.ui.dialog.ShowOrderPriceDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowRewardNoticeDialog
import com.haoshuang.zhouzhoubang.ui.dialog.Ts10Dialog
import com.haoshuang.zhouzhoubang.ui.dialog.Tx2Dialog
import com.haoshuang.zhouzhoubang.ui.page.home.settings.rate.TeamRateSetActivity
import com.haoshuang.zhouzhoubang.utils.MediaPlayUtils
import com.haoshuang.zhouzhoubang.utils.NavigationUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseBindingHolder
import com.mufeng.libs.base.BaseBindingQuickAdapter
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.copyToClipboard
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.vertical
import com.mufeng.libs.utils.view.visibleOrGone


/**
 * 抢单详情
 */
class ReceiveOrderDetailActivity :
    BaseVMActivity<ReceiveOrderDetailViewModel, ActivityReceiveOrderDetailBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<ReceiveOrderDetailActivity>()
        }
    }

    private var pay_price = ""
    private var store_order_tel = ""
    private var detailBean: DetaiBean? = null
    private var order_id = ""

    private val data = arrayListOf<Image2Bean>()
    private val adapter = ImageAdapter23(data)

    private var cate_id = 0
    private var tcate_id = 0

    // 不感兴趣标签
    private val unlikeTagList = arrayListOf<String>()

    override fun initIntent() {
        order_id = intent.getString("order_id")
    }

    override fun initView(savedInstanceState: Bundle?) {

        binding.titleBar.title = "订单详情"
        binding.titleBar.leftImageView().click { finish() }

        binding.recyclerView.vertical(4)
            .adapter = adapter
        adapter.setOnItemClick { view, position, item ->
            if (item == null) return@setOnItemClick
            if (item.isVideo == 0) {
                startPage<LookActivity>("imgBeen" to data.map { it.image }, "position" to position)
            } else {
                startPage<VideoActivity>("url" to item.image)
            }
        }

        binding.blZb.clickWithTrigger {
            startPage<WarrantyActivity>("ids" to detailBean?.id)
        }
// 点击查看价格
        binding.tvPrice.clickWithTrigger {
            if (detailBean != null) {
                XPopup.Builder(mActivity)
                    .asCustom(
                        ShowOrderPriceDialog(
                            context = mActivity,
                            prepayments_amount = detailBean!!.prepayments_amount.toString(),
                            nightPrice = "${detailBean!!.nighttime_amount}",
                            totalPrice = detailBean!!.pay_price,
                            teamPrice = "",
                            teamLeaderPrice = "",
                            teamMemberPrice = "",
                            minePrice = detailBean!!.pay_price,
                        )
                    )
                    .show()
            }
        }
        // 不感兴趣
        binding.tvBg.clickWithTrigger {
            XPopup.Builder(mActivity)
                .asCustom(BgxDialog(mActivity, unlikeTagList) { tag, remark ->
                    vm.addUnlikeOrder(order_id, tag, remark)
                })
                .show()
        }

        /// 奖励须知
        binding.llRewardView.clickWithTrigger {
            XPopup.Builder(mActivity)
                .asCustom(ShowRewardNoticeDialog(mActivity))
                .show()
        }

        binding.ivNavigation.clickWithTrigger {
            // 进行导航
            // 获取手机已安装的地图应用 腾讯, 高德, 百度
            NavigationUtils.startNavigation(
                mActivity,
                detailBean?.lat ?: "",
                detailBean?.lng ?: "",
                detailBean?.user_address ?: ""
            )
        }

        binding.userAddress.clickWithTrigger {
            copyToClipboard(detailBean?.user_address ?: "")
            toast("服务地址复制成功")
        }

        // 抢单
        binding.tvCommit.clickWithTrigger {
//            if (AccountUtils.user?.team?.is_team_set == 1) {
            vm.verifyTakeTask(order_id)
            /*   } else {
                   XPopup.Builder(mActivity)
                       .asCustom(
                           ConfirmDialog(
                               context = mActivity,
                               title = "温馨提示",
                               content = "您还没有进行团队设置, 暂时无法接单, 请前往设置",
                               cancelStr = "取消",
                               confirmStr = "前往设置",
                               isHideCancel = false,
                               isHideAgain = false,
                               onCancel = {},
                               onConfirm = {
                                   startPage<StoreSettingsActivity>()
                               })
                       )
                       .show()
               }*/
        }

    }

    override fun initData() {
        vm.getMasterTakeTaskDetail(order_id)
        vm.getUnlikeTag()
    }

    override fun startObserve() {

        vm.getMasterTakeTaskDetailData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                detailBean = it
                setupData()
            }
        }

        vm.getUnlikeTagData.observeState(this) {
            onSuccess {
                unlikeTagList.clear()
                unlikeTagList.addAll(it ?: mutableListOf())
            }
        }

        vm.addUnlikeOrderData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                finish()
            }
        }

        vm.verifyTakeTaskData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code == "1003") {
                    XPopup.Builder(mActivity)
                        .asCustom(Tx2Dialog(mActivity) {
                            if (it == 0) {
                                val baoXianFee =
                                    if (AccountUtils.user?.insurance_status == "1" && AccountUtils.user?.insurance_type == "1") detailBean?.deduct_insurance_amount else null
                                if (detailBean?.is_cart_order == 1) {
                                    XPopup.Builder(this@ReceiveOrderDetailActivity)
                                        .asCustom(
                                            QdDialog4(
                                                this@ReceiveOrderDetailActivity,
                                                detailBean,
                                                baoXianFee ?: ""
                                            ) {
                                                vm.masterTakeTask(detailBean?.id.toString())
                                            })
                                        .show()
                                } else {
                                    XPopup.Builder(mActivity)
                                        .asCustom(
                                            QdDialog2(
                                                mActivity,
                                                detailBean?.pay_price ?: "",
                                                baoXianFee
                                            ) {
                                                vm.masterTakeTask(detailBean?.id.toString())
                                            })
                                        .show()
                                }
                            } else {
                                startPage<BondActivity55>(
                                    "team_id" to (AccountUtils.user?.team_id?.toIntOrNull() ?: 0)
                                )
                            }

                        })
                        .show()
                } else if (code == "1002") {
                    // 当门店未设置分成比例时接单提示
                    XPopup.Builder(mActivity)
                        .asCustom(
                            ConfirmDialog(
                                context = mActivity,
                                title = "温馨提示",
                                content = "您创建的门店当前未设置分成比例\n无法进行抢单，请设置后在进行抢单",
                                cancelStr = "取消",
                                confirmStr = "去设置",
                                isHideCancel = false,
                                onCancel = {},
                                onConfirm = {
                                    startPage<TeamRateSetActivity>()
                                })
                        )
                        .show()
                } else {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                val baoXianFee =
                    if (AccountUtils.user?.insurance_status == "1" && AccountUtils.user?.insurance_type == "1") detailBean?.deduct_insurance_amount else null
             /*   XPopup.Builder(mActivity)
                    .asCustom(QdDialog2(mActivity, pay_price, baoXianFee) {
                        vm.masterTakeTask(order_id)
                    })
                    .show()*/
                if (detailBean?.is_cart_order == 1) {
                    XPopup.Builder(this@ReceiveOrderDetailActivity)
                        .asCustom(
                            QdDialog4(
                                this@ReceiveOrderDetailActivity,
                                detailBean,
                                baoXianFee ?: ""
                            ) {
                                vm.masterTakeTask(detailBean?.id.toString())
                            })
                        .show()
                } else {
                    XPopup.Builder(mActivity)
                        .asCustom(
                            QdDialog2(
                                mActivity,
                                detailBean?.pay_price ?: "",
                                baoXianFee
                            ) {
                                vm.masterTakeTask(detailBean?.id.toString())
                            })
                        .show()
                }
            }
        }

        vm.masterTakeTaskData.observeState(this) {
            onLoading {
                showLoading()
            }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
                if ("未认证当前服务技能" == msg) {
                    XPopup.Builder(mActivity)
                        .asCustom(
                            Ts10Dialog(
                                mActivity
                            ) {
                                vm.masterGetSkill(order_id)
                            })
                        .show()
                }
            }
            onSuccess {
                dismissLoading()
                MediaPlayUtils.playTakeOrderSuccess()
                XPopup.Builder(mActivity)
                    .asCustom(
                        QdDialog(
                            mActivity,
                            it?.confirm_residue_time.toString()
                        ) {
                            if (detailBean?.is_team == "0") {
                                startPage<AppointmentCustomerActivity>("ids" to it?.oid)
                            } else {
                                startPage<AppointmentCustomerActivity2>("ids" to it?.oid)
                            }
                            LiveEventBus.get(ReceiveOrderSuccess::class.java)
                                .post(ReceiveOrderSuccess())
                            LiveEventBus.get(RefreshHomeOrderEvent::class.java)
                                .post(RefreshHomeOrderEvent())
                            finish()
                        })
                    .show()
                vm.getMasterTakeTaskDetail(order_id)
            }
        }

        vm.masterGetSkillData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    if (detailBean?.is_team == "0") {
                        cate_id = it.cate_id
                        tcate_id = it.tcate_id
                        vm.verifyService(it.cate_id.toString(), it.tcate_id.toString())
                    } else {
                        startPage<SelectSkillsActivity3>(
                            "cate_id" to it.cate_id,
                            "tcate_id" to it.tcate_id,
                            "fcate_id" to it.fcate_id
                        )
                    }
                }
            }
        }

        vm.verifyServiceData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                startPage<ExaminationActivity2>("ids" to tcate_id, "ids2" to cate_id)
            }
        }

    }

    /**
     * 设置详情数据
     */
    private fun setupData() {
        if (detailBean != null) {

            binding.apply {
                ivHead.load(detailBean!!.user_avatar, R.mipmap.rl)
                realName.text = detailBean!!.real_name
                tvJl.text = "距您常用位置约${detailBean!!.distance}km（仅供参考）"
                userAddress.text = detailBean!!.user_address
                tvMark.text = detailBean!!.mark
                store_order_tel = detailBean!!.user_phone
                pay_price = detailBean!!.pay_price
                if (detailBean!!.hourly_worker_time.isBlank()) {
                    storeName.text = "${detailBean!!.store_name}"
                } else {
                    if (detailBean!!.hourly_worker_time == "0") {
                        storeName.text = "${detailBean!!.store_name}"
                    } else {
                        storeName.text =
                            "${detailBean!!.store_name} ${detailBean!!.hourly_worker_time}小时"
                    }
                }
                // storeName.text=it.store_name
                tvorderId.text = detailBean!!.order_id
                tvPrice.text = detailBean!!.pay_price
                addOrderTime.text = detailBean!!.add_order_time
                serviceTime.text = detailBean!!.service_time
                tvGuarantee.text = "服务质保期(${detailBean!!.guarantee}天)"

                /// 奖励金是否显示
                llRewardView.visibleOrGone(0.0 != detailBean!!.reward_amount.toDoubleOrNull())
                tvRewardMoney.text = "${detailBean!!.reward_amount}元"

                val nighttime_amount = detailBean!!.nighttime_amount?.toDoubleOrNull() ?: 0.0
                llNighttimeAmount.visibleOrGone(nighttime_amount > 0.0)
                tvNighttimeAmount.text = "${detailBean!!.nighttime_amount}元"

                tvTotalNum.text = "数量 x${detailBean?.total_num.toString()}"

                tvKeyArea.text = "重点区域: ${detailBean?.key_areas}"
                tvKeyArea.visibleOrGone(!detailBean?.key_areas.isNullOrEmpty())


                if (detailBean?.is_cart_order == 1) {
                    binding.recyclerViewSeriviceItem.visibility = View.VISIBLE
                    if (!detailBean?.order_goods.isNullOrEmpty()) {
                        binding?.tvServiceNum?.text =
                            "共" + detailBean?.order_goods?.size + "项服务明细"
                        var serviceItemAdapter = ServiceItemAdapter(detailBean?.order_goods!!)
                        binding.recyclerViewSeriviceItem.layoutManager = LinearLayoutManager(
                            this@ReceiveOrderDetailActivity,
                            LinearLayoutManager.VERTICAL, false
                        )
                        binding.recyclerViewSeriviceItem.adapter = serviceItemAdapter
                    }
                    binding.storeName.visibility = View.GONE
                } else {
                    binding.recyclerViewSeriviceItem.visibility = View.GONE
                    binding.storeName.visibility = View.VISIBLE
                }


            }
            data.clear()
            for (b in detailBean!!.images) {
                if (b.isNotBlank())
                    data.add(Image2Bean(b, 0))
            }
            if (detailBean!!.video.isNotBlank()) {
                data.add(Image2Bean(detailBean!!.video, 1))
            }
            adapter.notifyDataSetChanged()
        }
    }

}

class ServiceItemAdapter(data: MutableList<OrderGoodsBean>) :
    BaseBindingQuickAdapter<OrderGoodsBean, ItemServiceItemDetailBinding>(data) {

    override fun onBindViewHolder(holder: BaseBindingHolder, position: Int, item: OrderGoodsBean?) {
        val binding = ItemServiceItemDetailBinding.bind(holder.itemView)
        binding.tvGoodsName.text = item?.goods_name
        binding.tvProductAttrName.text = item?.product_attr_name
        binding.tvNum.text ="x"+ item?.num.toString()
        binding.tvMoney.text = "¥" + item?.money
    }
}